// 预设的颜色主题
const colorThemes = {
  level1: { background: '#3498db', border: '#2980b9' },
  level2: { background: '#2ecc71', border: '#27ae60' },
  level3: { background: '#e67e22', border: '#d35400' },
  level4: { background: '#e74c3c', border: '#c0392b' },
  level5: { background: '#9b59b6', border: '#8e44ad' }
}

// 生成连线颜色
const getEdgeColor = (sourceLevel, targetLevel) => {
  // 获取源节点和目标节点的主题色
  const sourceTheme = colorThemes[`level${sourceLevel}`] || colorThemes.level1
  const targetTheme = colorThemes[`level${targetLevel}`] || colorThemes.level1
  
  // 使用渐变色
  return {
    stroke: targetTheme.background,
    strokeWidth: 2,
    // 如果是相邻层级，使用动画效果
    animated: Math.abs(targetLevel - sourceLevel) === 1
  }
}

// 布局配置
const layoutConfig = {
  nodeWidth: 150,
  nodeHeight: 50,
  levelGap: 150,    // 层级之间的垂直间距
  baseNodeGap: 250, // 基础节点间距
  topPadding: 50,   // 顶部留白
  minNodeGap: 150   // 最小节点间距
}

// 计算每个节点的总宽度（包含其所有子节点）
const calculateNodeWidth = (node, level = 1) => {
  if (!node.children || node.children.length === 0) {
    return layoutConfig.baseNodeGap
  }

  const childrenWidths = node.children.map(child => calculateNodeWidth(child, level + 1))
  const totalChildrenWidth = childrenWidths.reduce((sum, width) => sum + width, 0)

  // 确保父节点宽度至少大于等于所有子节点宽度之和
  return Math.max(layoutConfig.baseNodeGap, totalChildrenWidth)
}

// 计算每层节点的位置信息
const calculateNodePositions = (nodes, level = 1, startX = 0, parentWidth = null) => {
  const positions = []

  if (nodes.length === 0) return positions

  // 计算当前层所有节点的总宽度
  const nodeWidths = nodes.map(node => calculateNodeWidth(node, level))
  const totalWidth = nodeWidths.reduce((sum, width) => sum + width, 0)

  // 如果有父节点宽度，使用父节点宽度居中布局
  const actualStartX = parentWidth ? startX + (parentWidth - totalWidth) / 2 : startX
  let currentX = actualStartX

  nodes.forEach((node, index) => {
    const nodeWidth = nodeWidths[index]
    const x = currentX + nodeWidth / 2

    positions.push({
      id: node.id,
      x,
      y: layoutConfig.topPadding + (level - 1) * layoutConfig.levelGap,
      width: nodeWidth
    })

    // 递归处理子节点
    if (node.children && node.children.length > 0) {
      positions.push(...calculateNodePositions(
        node.children,
        level + 1,
        currentX,
        nodeWidth
      ))
    }

    currentX += nodeWidth
  })

  return positions
}

// 将JSON结构转换为Vue-Flow元素
const convertJsonToElements = (json) => {
  const elements = []
  const positions = calculateNodePositions(json)
  const positionMap = new Map(positions.map(pos => [pos.id, pos]))

  const processNode = (nodes, level = 1, parentId = null) => {
    nodes.forEach(node => {
      const pos = positionMap.get(node.id)
      if (!pos) return

      // 创建节点
      elements.push({
        id: node.id,
        label: node.label,
        position: { x: pos.x, y: pos.y },
        class: `level-${level}-node`,
        data: { level }
      })

      // 创建与父节点的连线
      if (parentId) {
        const edgeStyle = getEdgeColor(level - 1, level)
        elements.push({
          id: `e-${parentId}-${node.id}`,
          source: parentId,
          target: node.id,
          type: 'smoothstep',
          animated: edgeStyle.animated,
          style: {
            stroke: edgeStyle.stroke,
            strokeWidth: edgeStyle.strokeWidth
          }
        })
      }

      // 递归处理子节点
      if (node.children && node.children.length > 0) {
        processNode(node.children, level + 1, node.id)
      }
    })
  }

  processNode(json)
  return elements
}

export { convertJsonToElements }
